#include <stdint.h>
#include "../libc/function.h"
#include "../libc/string.h"
#include "../cpu/port.h"
#include "../cpu/isr.h"
#include "screen.h"
#include "../kernel/kernel.h"
#include "keyboard.h"

#define MAX_CODE 57
#define BACKSPACE 0x0e
#define ENTER 0x1c

const char sc_ascii[] = { '?', '?', '1', '2', '3', '4', '5', '6',     
    '7', '8', '9', '0', '-', '=', '?', '?', 'q', 'w', 'e', 'r', 't', 'y', 
        'u', 'i', 'o', 'p', '[', ']', '?', '?', 'a', 's', 'd', 'f', 'g', 
        'h', 'j', 'k', 'l', ';', '\'', '`', '?', '\\', 'z', 'x', 'c', 'v', 
        'b', 'n', 'm', ',', '.', '/', '?', '?', '?', ' '};
static char line[256];

static uint32_t keyboard_callback(isr_registers_t *reg) {
    uint8_t scanCode = port_byte_in(0x60);
    if(scanCode > MAX_CODE) {
        return (uint32_t)reg;
    } else if (scanCode == BACKSPACE) {
        kprint_backspace();
        backspace(line);
    } else if (scanCode == ENTER) {
        kprint("\n");
        user_input(line);
        line[0] = '\0';
    } else {
        char letter = sc_ascii[scanCode];
        char str[2] = {letter, '\0'};
        kprint(str);
        append(line, letter);
    }
    
    // UNUSED(reg);
    return (uint32_t)reg;
}

void init_keyboard() {
    isr_handler_register(IRQ1, keyboard_callback);
}